<template>
	<BackgroundImage>
		<!-- 顶部导航 -->
		<TopNavigation title="" backText="首页" />

		<view class="match-query-container">

			<BoxView style="height: 100%;padding: 20rpx 10rpx;">
				<view class="container-main">
					<view class="container-left">
						<view class="container-left-all">
							<view class="container-left-all-title">
								<image src="/static/mofan.png" mode="aspectFit"></image>
								<text>赛事总数</text>
							</view>
							<text class="value_text">{{ matchStats.totalMatches }}</text>
							<image src="/static/back_icon1.png" mode="aspectFit" class="back_icon1"></image>
						</view>
						<view class="container-left-loading">
							<view class="container-left-all-title">
								<image src="/static/mofan.png" mode="aspectFit"></image>
								<text>进行中赛事</text>
							</view>
							<text class="value_text">{{ matchStats.activeMatches }}</text>
							<image src="/static/back_icon1.png" mode="aspectFit" class="back_icon1"></image>
						</view>
						<view class="container-left-button">
							<view class="container-left-button-item1" @click="initMatch">初始化赛事</view>
							<view class="container-left-button-item2" @click="initMatchPro">初始化赛程</view>
							<view class="container-left-button-item3" @click="goToManageModels">模式管理</view>
							<view class="container-left-button-item4" @click="goToCreateMatch">创建赛事</view>
							<image src="/static/back_icon2.png" mode="aspectFit" class="back_icon2"></image>
						</view>
					</view>
					<view class="container-right">
						<view class="container-right-title">
							<text></text>
							<text>赛事列表</text>
							<text>共 {{ matchList.length }} 个赛事</text>
						</view>
						<view class="container-right-list">
							<view class="container-right-list-item" v-for="match in matchList" :key="match.id">
								<view class="_name"><text>{{ match.name }}</text><text
										:class="getStatusClass(match.status)">{{ getStatusText(match.status) }}</text>
								</view>
								<view class="_id"><text>赛事ID：</text>{{ match.id }}</view>
								<view class="_createUserID"><text>创建者：</text>{{ match.createUserID }}</view>
								<view class="_sponsor"><text>赞助商：</text>{{ match.sponsor || '无' }}</view>
								<view class="_startTime"><text>开始时间：</text>{{ formatDate(match.startTime) }}</view>
								<view class="_endTime"><text>结束时间：</text>{{ formatDate(match.endTime) }}</view>
								<view class="_scheduleCount"><text>赛程数量：</text>{{ match.scheduleCount || 0 }} 个</view>
								<view class="container-right-list-item-button">
									<view class="container-right-list-item-button-item1"
										@click.stop="viewSchedules(match)">查看赛程</view>
									<view class="container-right-list-item-button-item2"
										@click.stop="viewMatchModels(match)">比赛模式</view>
									<view class="container-right-list-item-button-item3" @click.stop="editMatch(match)">编辑</view>
								</view>
							</view>
						</view>

					</view>
				</view>
			</BoxView>

			<PopuleView v-model="showInitMatchDialog" title="初始化赛事" description="确定要初始化所有赛事吗？此操作将重置赛事状态。"
				submit-text="确认初始化" @submit="confirmInitMatch" />
			<PopuleView v-model="showInitMatchProDialog" title="初始化赛程" description="确定要初始化所有赛程吗？此操作将重置赛程状态。"
				submit-text="确认初始化" @submit="confirmInitMatchPro" />



		</view>
	</BackgroundImage>
</template>

<script setup>
import BackgroundImage from "@/components/BackgroundImage.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import BoxView from "@/components/UiView/BoxView.vue";
import PopuleView from "@/components/UiView/PopuleView.vue";
import {
	ref,
	onMounted
} from 'vue'
import { onShow } from '@dcloudio/uni-app'
import {
	MatchAPI,
	BattleAPI
} from '@/api/battle.js'

// 响应式数据
const loading = ref(false)
const matchList = ref([])
const showInitMatchDialog = ref(false)
const showInitMatchProDialog = ref(false)

// 统计数据
const matchStats = ref({
	totalMatches: 0,
	totalSchedules: 0,
	activeMatches: 0
})

// 查询参数
const queryParams = ref({
	name: '',
	status: '',
	statusIndex: 0,
	startDate: '',
	endDate: '',
	pageNum: 0,
	pageSize: 10
})

// 分页信息
const currentPage = ref(1)
const totalPages = ref(1)

// 状态选项
const statusOptions = ['全部', '待开始', '进行中', '已结束']

// 状态映射
const statusMap = {
	0: '待开始',
	1: '进行中',
	2: '已结束'
}

// 状态样式映射
const statusClassMap = {
	0: 'status-pending',
	1: 'status-active',
	2: 'status-finished'
}

// 获取状态文本
const getStatusText = (status) => {
	return statusMap[status] || '未知'
}

// 获取状态样式
const getStatusClass = (status) => {
	return statusClassMap[status] || 'status-unknown'
}

// 格式化日期
const formatDate = (timestamp) => {
	if (!timestamp) return '未设置'
	const date = new Date(timestamp)
	return date.toLocaleString('zh-CN')
}

// 状态选择变化
const onStatusChange = (e) => {
	const index = e.detail.value
	queryParams.value.statusIndex = index
	queryParams.value.status = index === 0 ? '' : index - 1
}

// 开始日期变化
const onStartDateChange = (e) => {
	queryParams.value.startDate = e.detail.value
}

// 结束日期变化
const onEndDateChange = (e) => {
	queryParams.value.endDate = e.detail.value
}

// 查询赛事
const queryMatches = async () => {
	loading.value = true
	try {
		// 构建查询参数
		const params = {
			pageNum: queryParams.value.pageNum,
			pageSize: queryParams.value.pageSize
		}

		if (queryParams.value.name) {
			params.name = queryParams.value.name
		}

		if (queryParams.value.status !== '') {
			params.status = queryParams.value.status
		}

		if (queryParams.value.startDate) {
			params.startTime = new Date(queryParams.value.startDate).getTime()
		}

		if (queryParams.value.endDate) {
			params.endTime = new Date(queryParams.value.endDate + ' 23:59:59').getTime()
		}

		const result = await MatchAPI.page(params)
		console.log('赛事查询API返回结果:', result)

		if (result.code === 0) {
			matchList.value = result.data || []
			totalPages.value = result.data && result.data.length > 0 ? currentPage.value : 1
			currentPage.value = queryParams.value.pageNum + 1

			// 更新统计数据
			updateStats()

			uni.showToast({
				title: '查询成功',
				icon: 'success'
			})
		} else {
			throw new Error(result.msg || '查询失败')
		}
	} catch (error) {
		console.error('查询赛事失败:', error)
		uni.showToast({
			title: error.message || '查询失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 重置查询
const resetQuery = () => {
	queryParams.value = {
		name: '',
		status: '',
		statusIndex: 0,
		startDate: '',
		endDate: '',
		pageNum: 0,
		pageSize: 10
	}
	queryMatches()
}

// 切换页面
const changePage = (page) => {
	if (page < 1 || page > totalPages.value) return

	queryParams.value.pageNum = page - 1
	queryMatches()
}

// 显示赛事详情
const showMatchDetail = (match) => {
	// 这里可以跳转到详情页面或显示详情弹窗
	uni.showModal({
		title: '赛事详情',
		content: `赛事名称: ${match.name}\n赛事ID: ${match.id}\n描述: ${match.desc || '无'}`,
		showCancel: false
	})
}

// 查看赛程
const viewSchedules = (match) => {
	uni.navigateTo({
		url: `/views/schedule-query/schedule-query?matchId=${match.id}&matchName=${encodeURIComponent(match.name)}`
	})
}

// 查看比赛模式
const viewMatchModels = (match) => {
	uni.navigateTo({
		url: `/views/match-model-manage/match-model-manage?matchId=${match.id}&matchName=${encodeURIComponent(match.name)}`
	})
}

// 编辑赛事
const editMatch = (match) => {
	// 使用全局存储传递赛事数据，不通过链接参数
	try {
		console.log('准备存储编辑数据:', match)
		// 确保数据可以被序列化，创建一个纯对象副本
		const matchData = {
			id: match.id,
			matchId: match.matchId || match.id,
			name: match.name,
			startTime: match.startTime,
			endTime: match.endTime,
			desc: match.desc,
			sponsor: match.sponsor,
			status: match.status,
			matchModel: match.matchModel,
			matchModelId: match.matchModelId,
			createUserID: match.createUserID,
			scheduleCount: match.scheduleCount
		}
		uni.setStorageSync('editMatchData', matchData)
		console.log('数据已存储，准备跳转')
		// 跳转到创建/编辑页面
		uni.navigateTo({
			url: '/views/match-query/match-create',
			success: () => {
				console.log('页面跳转成功')
			},
			fail: (err) => {
				console.error('页面跳转失败:', err)
			}
		})
	} catch (error) {
		console.error('存储编辑数据失败:', error)
		uni.showToast({
			title: '操作失败，请重试',
			icon: 'none'
		})
	}
}

// 跳转到创建赛事页面
const goToCreateMatch = () => {
	uni.navigateTo({
		url: '/views/match-query/match-create'
	})
}

// 初始化赛事
const initMatch = () => {
	showInitMatchDialog.value = true
}
// 初始化赛程
const initMatchPro = () => {
	showInitMatchProDialog.value = true
}
// 确认初始化赛程
const confirmInitMatch = async () => {
	showInitMatchDialog.value = false
	loading.value = true
	try {
		const result = await BattleAPI.initSchdule({})
		if (result.code === 0) {
			uni.showToast({
				title: '赛程初始化成功',
				icon: 'success'
			})
			queryMatches()
		} else {
			throw new Error(result.msg || '初始化失败')
		}
	} catch (error) {
		uni.showToast({
			title: error.message || '初始化失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}
const confirmInitMatchPro = async () => {
	showInitMatchProDialog.value = false
	loading.value = true
	try {
		const result = await BattleAPI.initMatch({ })
		if (result.code === 0) {
			uni.showToast({
				title: '赛事初始化成功',
				icon: 'success'
			})
			queryMatches()
		} else {
			throw new Error(result.msg || '初始化失败')
		}
	} catch (error) {
		uni.showToast({
			title: error.message || '初始化失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
} 

// 跳转到模式管理页面
const goToManageModels = () => {
	uni.navigateTo({
		url: '/views/match-model-manage/match-model-manage'
	})
}

// 更新统计数据
const updateStats = () => {
	const totalMatches = matchList.value.length
	const activeMatches = matchList.value.filter(match => match.status === 1).length
	const totalSchedules = matchList.value.reduce((sum, match) => sum + (match.scheduleCount || 0), 0)

	matchStats.value = {
		totalMatches,
		totalSchedules,
		activeMatches
	}
}

// 页面加载时执行查询
onMounted(() => {
	queryMatches()
})

// 页面显示时检查是否需要刷新数据
onShow(() => {
	// 检查是否有刷新标记（编辑或创建成功后设置）
	const needRefresh = uni.getStorageSync('matchListNeedRefresh')
	if (needRefresh) {
		console.log('检测到需要刷新赛事列表')
		// 清除刷新标记
		uni.removeStorageSync('matchListNeedRefresh')
		// 刷新数据
		queryMatches()
	}
})
</script>

<style lang="scss" scoped>
.match-query-container {
	height: calc(100vh - 55rpx);
	padding: 0 30rpx;
	position: relative;
	box-sizing: border-box;
	padding-bottom: 20rpx;
}

.container-main {
	display: flex;
	justify-content: space-between;
	height: 100%;
	overflow: auto;
	align-items: stretch;

	.container-right {
		border-radius: 12rpx;
		border: 4rpx solid #2ADBE4;
		background: #FFFFF4;
		display: flex;
		flex-direction: column;
		height: 300rpx;
		overflow: auto;

		&-list {
			margin: 10rpx 15rpx 10rpx 10rpx;
			flex: none;

			&-item {
				background: #F0F0E4;
				padding: 10rpx;
				margin-bottom: 10rpx;

				&-button {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-top: 10rpx;

					&-item1,
					&-item2,
					&-item3 {
						width: 33.33%;
						box-sizing: border-box;
						height: 30rpx;
						font-size: 14rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						padding-bottom: 4rpx;
					}

					&-item1 {
						background: url('/static/buttons/button5.png') no-repeat center center;
						background-size: 100% 100%;
						color: #005918;
					}

					&-item2 {
						background: url('/static/buttons/button6.png') no-repeat center center;
						background-size: 100% 100%;
						color: #9B3B18;
					}

					&-item3 {
						background: url('/static/buttons/button7.png') no-repeat center center;
						background-size: 100% 100%;
						color: #fff;
					}
				}

				._id,
				._createUserID,
				._sponsor,
				._startTime,
				._endTime,
				._scheduleCount {
					font-size: 14rpx;
					margin-top: 5rpx;

					text {
						display: inline-block;
						font-size: 14rpx;
						color: #99A1A4;
						width: 70rpx;
						text-align: right;
					}
				}

				._name {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 14rpx;

					text {
						font-size: 16rpx;
						font-weight: bold;

						&:nth-child(2) {
							color: #fff;
							font-size: 12rpx;
							background: #3D85EC;
							border-radius: 12rpx;
							padding: 2rpx 10rpx;

							&.status-pending {
								background: #fff3cd;
								color: #856404;
							}

							&.status-active {
								background: #336b40;
								color: #155724;
							}

							&.status-finished {
								background: #f8d7da;
								color: #721c24;
							}
						}
					}
				}
			}

			text {
				font-size: 16rpx;
			}
		}

		&-title {
			display: flex;
			justify-content: center;
			align-items: center;
			background: #3D85EC;
			border-radius: 8rpx 8rpx 0 0;
			padding: 5rpx 10rpx;
			position: relative;

			text {
				color: #fff;

				&:nth-child(1) {
					display: none;
				}

				&:nth-child(2) {
					font-size: 16rpx;
				}

				&:nth-child(3) {
					position: absolute;
					right: 10rpx;
					font-size: 12rpx;
					font-weight: 200;
				}
			}

			// font-size: 20rpx;
		}
	}

	.container-left {
		height: 100%;
		display: flex;
		flex-direction: column;

		&-button {
			width: 320rpx;
			height: 190rpx;
			padding: 24rpx 20rpx 24rpx 30rpx;
			background: url('/static/back/back2.png') no-repeat center center;
			background-size: 100% 100%;
			display: flex;
			flex-wrap: wrap;
			box-sizing: border-box;
			justify-content: space-between;
			// align-content: space-between;
			row-gap: 0rpx;
			position: relative;
			font-size: 16rpx;

			// margin-bottom: 10rpx;
			&-item1,
			&-item2,
			&-item3,
			&-item4 {
				width: calc(50% - 6rpx);
				height: 50rpx;
				box-sizing: border-box;
				padding-bottom: 8rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				text-shadow: 0px 3px 4px rgba(0, 0, 0, 0.22);
			}

			&-item1 {
				margin-top: 10rpx;
				background: url('/static/buttons/button1.png') no-repeat center center;
				background-size: 100% 100%;
			}

			&-item2 {
				margin-top: 10rpx;
				background: url('/static/buttons/button2.png') no-repeat center center;
				background-size: 100% 100%;
			}

			&-item3 {
				background: url('/static/buttons/button3.png') no-repeat center center;
				background-size: 100% 100%;
			}

			&-item4 {
				background: url('/static/buttons/button4.png') no-repeat center center;
				background-size: 100% 100%;
			}

			.back_icon2 {
				width: 54rpx;
				height: 34rpx;
				position: absolute;
				right: 50%;
				transform: translateX(50%);
				top: -15rpx;
			}
		}

		&-all,
		&-loading {
			width: 250rpx;
			height: 65rpx;
			// padding-left: 36rpx;
			// padding-right: 36rpx;
			background: url('/static/back/back1.png') no-repeat center center;
			background-size: 100% 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: relative;
			margin-bottom: 10rpx;
			padding: 10rpx 30rpx;

			&-title {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 2rpx;
				}

				text {
					font-size: 18rpx;
					color: #646464;
					font-weight: bold;
				}
			}

			.value_text {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 37rpx;
				height: 37rpx;
				background: #E4F1FF;
				border-radius: 6rpx;
				border: 2rpx solid #6193FF;
				font-size: 24rpx;
				color: #FF8000;
				font-weight: bold;
				margin-bottom: 10rpx;
			}

			.back_icon1 {
				position: absolute;
				right: 0;
				top: -15rpx;
				width: 40rpx;
				height: 50rpx;

			}
		}
	}
}
</style>